import playingStore from '@/store/playing';
import dyUserPlayingService from "@/api/dyUserPlayingService";
import CryptoJS from 'crypto-js';
const playing = playingStore()
const adUnitId = ref("5v3s9jvqk0nb05lx76")
const adId = ref("jnmpzk4hxz7l4lv8rt")

export const adAPI = (ad:any,ads:any) => {
    ad.value = uni.createRewardedVideoAd({
      adUnitId: adUnitId.value,
    });
    ad.value.onError((err:any) => {
      switch (err.errCode) {
        case 1004:
          console.log("无合适的广告");
          // 在此处添加适当的提示或处理逻辑
          ads.value = 2
          break;
        default:
          console.log("发生错误，错误码：" + err.errCode);
          ads.value = 2
          // 更多错误处理逻辑
      }
    });
  
    ad.value.onClose((data:any) => {
      if (data.isEnded) {
        // 判断是否是用户进来的
        if(playing.userId && playing.inUser){
          var s = CryptoJS.AES.encrypt(JSON.stringify({"userId":playing.userId,playingId:Number(playing.playingId)}), CryptoJS.enc.Base64.parse("XjjkaLnlzAFbR399IP4kdQ=="), {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7,
            length: 128
        }).toString();
        var timestamp = new Date().getTime();
        var sign = CryptoJS.SHA1(s + timestamp  + "QGZUanpSaSy9DEPQFVULJQ==").toString();
        dyUserPlayingService.userComplete({
            s:s,
            sign:sign,
            timestamp:timestamp
          })
        }
        ads.value = 1
      } else {
        console.log("未观看完视频");
        ads.value = 2
      }
    });
  
    ad.value.load();
  }
  // 弹屏
  export const adPopAPI = (ad:any) => {
    ad.value = uni.createInterstitialAd({
      adUnitId: adId.value,
    });
  
    ad.value.onError((err:any) => {
      switch (err.errCode) {
        case 1004:
          console.log("无合适的广告");
    
       
          break;
        default:
          console.log("发生错误，错误码：" + err.errCode);
         
      }
    });
  
    ad.value.onClose((data:any) => {
      if (data.isEnded) {
        console.log(data);
        console.log("观看了", data.count, "个视频");
      } else {
        console.log("未观看完视频");
      }
    });
  
    ad.value.load();
  }

  export 


  const header = ref({
    'Cookie':'Hm_lvt_d50c3c9cd85f1ae74470bba96564acf9=1709878611; Hm_lpvt_d50c3c9cd85f1ae74470bba96564acf9=1709878611',
    'Content-Type':'application/x-www-form-urlencoded'
  })

  export const homophony = async (text: string) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: "https://www.dmnuo.com/douyin/answer/",
        method: 'POST',
        header: header.value,
        data: {
          id: text,
          zhenbi: 20191123
        },
        success: (res) => {
          const regex = /"info":(\[[^\]]+\])/;
          const match = res.data.toString().match(regex);
          if (match && match.length > 1) {
            const infoString = match[1];
            const infoArray = JSON.parse(infoString);
            const randomIndex = Math.floor(Math.random() * infoArray.length);
            const firstElement = infoArray[randomIndex];
            resolve(firstElement);
          } else {
            reject("No matching data found");
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  export const getAnswer = async () => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: "https://answer.hi2future.com/Book/get_answer?lang=zh-CN",
        success: (res:any) => {
        resolve(res.data.result.answer.content);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  export const onlinebmicalculator = async (height:number,weight:number)=>{
    return new Promise((resolve, reject) => {
      uni.request({
        url: "https://cn.onlinebmicalculator.com/",
        data: `f_submit=计算 BMI&f_autosave=1&f_def=def_chinese&f_weight=${weight}&f_height=${height}&f_units=units_is`,
        method: 'POST',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },

        success: (res:any) => {
          var regex = /data:\s*\[([^\]]+)\]/g;
          var matches = res.data.toString().match(regex) || [];
          var dataValues: string[] = [];
          matches.forEach(function(match:any) {
            var dataValue = match.match(/\[([^\]]+)\]/);
            if (dataValue && dataValue.length > 1) {
              dataValues.push(dataValue[1]);
            }
          });
        resolve(dataValues[1]);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  export const filtion = async (wordStr:string) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: "https://luckycola.com.cn/tools/sensiWords",
        method: 'POST',
        data:{
          ColaKey:'pVSyllHbzCiFbh1710209487517RpTBQ6wrIB',
          wordStr:wordStr,
          code: 1
        },
        success: (res:any) => {
        resolve(res.data.isPass);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 生肖匹配
   */
  export const sxpeidui = async(data:Array<number>)=>{
    return new Promise((resolve, reject) => {
      uni.request({
        url: "https://www.dmnuo.com/douyin/sxpeidui/",
        method: 'POST',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: `sign=${data[0] + 1}&signn=${data[1] + 1}`,
        success: (res:any) => {
        // 提取 keywords 内容
        var keywordsRegex = /<meta\s+name="keywords"\s+content="([^"]+)"\s*\/>/;
        var keywordsMatch = res.data.match(keywordsRegex);
        var keywords = '';
        if (keywordsMatch && keywordsMatch.length > 1) {
            keywords = keywordsMatch[1];
        }

        // 提取 description 内容
        var descriptionRegex = /<meta\s+name="description"\s+content="([^"]+)"\s*\/>/;
        var descriptionMatch = res.data.match(descriptionRegex);
        var description = '';
        if (descriptionMatch && descriptionMatch.length > 1) {
            description = descriptionMatch[1];
        }
        let infoData = [keywords,description]
        resolve(infoData);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }
  

  // export const birthday =  async (year:number,month:number,day:number) => {
  //   return new Promise((resolve, reject) => {
  //     const data = {
  //       submit: 1,
  //       yearType: 1,
  //       sdYear: year,
  //       sdMonth: month,
  //       sdDay: day,
  //     };
  //     const params = new URLSearchParams();
  //       for (const key in data) {
  //         params.append(key, data[key]);
  //       }
  //     uni.request({
  //       url: "https://www.smxs.com/shengrimima/index.html",
  //       method: 'POST',
  //       header:{
  //         'Content-Type':'application/x-www-form-urlencoded',
  //         'Cookie':'onethink_home_b_userInfo=think%3A%7B%22xingming%22%3A%22%22%2C%22frontType%22%3A%22%22%2C%22birthday%22%3A%22%22%2C%22yearType%22%3A%221%22%2C%22sdYear%22%3A%221964%22%2C%22sdMonth%22%3A%2203%22%2C%22sdDay%22%3A%2201%22%2C%22ldYear%22%3A%221964%22%2C%22ldMonth%22%3A%221%22%2C%22ldDay%22%3A%2218%22%2C%22xing%22%3A%22%22%2C%22ming%22%3A%22%22%2C%22sex%22%3A%22%22%2C%22year%22%3A%221964%22%2C%22month%22%3A%2203%22%2C%22day%22%3A%2201%22%2C%22hour%22%3A%2200%22%2C%22minute%22%3A%2200%22%2C%22cY%22%3A%22100%22%2C%22cM%22%3A%22782%22%2C%22cD%22%3A%2223445%22%2C%22cH%22%3A%22281220%22%2C%22term1%22%3A%224%252F%252803%25E6%259C%258806%25E6%2597%25A504%253A07%2529%22%2C%22term2%22%3A%225%252F%252803%25E6%259C%258821%25E6%2597%25A505%253A00%2529%22%2C%22start_term%22%3A%222149148%22%2C%22end_term%22%3A%22421672%22%2C%22start_term1%22%3A%222%252F%252802%25E6%259C%258805%25E6%2597%25A510%253A00%2529%22%2C%22end_term1%22%3A%224%252F%252803%25E6%259C%258806%25E6%2597%25A504%253A07%2529%22%2C%22lDate%22%3A%22%25E4%25B8%2580%25E4%25B9%259D%25E5%2585%25AD%25E5%259B%259B%25E5%25B9%25B4%25E6%25AD%25A3%25E6%259C%2588%25E5%258D%2581%25E5%2585%25AB%25E6%2597%25A5%22%2C%22lY%22%3A%22%25E4%25B8%2580%25E4%25B9%259D%25E5%2585%25AD%25E5%259B%259B%22%2C%22lM%22%3A%22%25E6%25AD%25A3%22%2C%22lD%22%3A%22%25E5%258D%2581%25E5%2585%25AB%22%2C%22old%22%3A%2260%22%2C%22xingzuo%22%3A%2211%22%2C%22xingzuoname%22%3A%22%25E5%258F%258C%25E9%25B1%25BC%25E5%25BA%25A7%22%2C%22xingzuourl%22%3A%22shuangyu%22%2C%22dateurl%22%3A%2231%22%2C%22xuexing%22%3A%22%22%2C%22shuxiang%22%3A%22%25E9%25BE%2599%22%2C%22sxid%22%3A%224%22%2C%22solarDate%22%3A%22%22%2C%22dateType%22%3A%220%22%2C%22dateText%22%3A%22%25E5%2585%25AC%25E5%258E%2586%253A%22%7D; expires=Thu, 28-Mar-2024 05:48:02 GMT; Max-Age=604800; path=/'
  //       },
  //       data: `submit=1&yearType=1&sdYear=${year}&sdMonth=${month}&sdDay=${day}`,
  //       success: (res:any) => {
  //       var re = /<p class="green">(.*?)<\/p>/;
  //       var contentRe = /<p>(.*?)<\/p>/g;
  //       var result = res.data.toString().match(re);
  //       var matches = res.data.toString().match(contentRe).slice(6, 33);
  //       // 将数组元素拼接成一个字符串
  //       var combinedString = matches.join("");
  //       combinedString = combinedString.replace(/<p>|<\/p>|<strong>|<\/strong>/g, "");
  //       result[0] = combinedString
  //       resolve(result);
  //       },
  //       fail: (error) => {
  //         reject(error);
  //       }
  //     });
  //   });
  // }
  export const birthday =  async (year:number,month:number,day:number) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `https://www.d1xz.net/sm/birthday/${month}-${day}.aspx`,
        method: 'GET',
        success: (res:any) => {
        var regex = /<p>([\s\S]*?)<\/p>/g;
        var regexH1 = /<h1>([\s\S]*?)<\/h1>/g;
        var matches = res.data.toString().match(regex).slice(0, 24);
        var combinedString = matches.join("");
        combinedString = combinedString.replace(/<p>|<\/p>|<strong>|<\/strong>/g, "");
        var matchesH1 = res.data.toString().match(regexH1);
        var result = []
        result[0] = combinedString
        result[1] = matchesH1.join("").replace(/<h1>|<\/h1>/g, "").split("生日：")[1];
        resolve(result);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }
  
  export const loveNAME = async (n1:string,n2:string) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: "https://www.qudou100.com/apis/xieyin/ql",
        method: 'POST',
        header: {
          'Content-Type':'application/x-www-form-urlencoded',
        },
        data:{
          n2:n2,
          n1:n1,
          from: 'web',
        },
        success: (res:any) => {
        resolve(res.data.data[0].oktxt);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  export const idiom = async (data:string) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `https://www.qudou100.com/chengyu/jielong/${data}.html`,
        success: (res:any) => {
        const regex = /<p class="mb-2 border-bottom">(.*?)<\/p>/g;
        let match;
        const results = [];

        while ((match = regex.exec(res.data)) !== null) {
            results.push(match[1]);
        }
        const regexContent = /<a\s.*?>(.*?)<\/a>/g;
        let matchItem;
        const resultData = [];
        while ((matchItem = regexContent.exec(results[0])) !== null) {
          resultData.push(matchItem[1]);
        }
        resolve(resultData);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  } 

  export const badyName = async(data:any)=>{
        return new Promise((resolve, reject) => {
      uni.request({
        url: 'https://www.zhiname.com/qm/qm.php',
        method: 'POST',
        header: {
          'Content-Type':'application/x-www-form-urlencoded',
        },
        data:{
          n:data[0],
          s:data[1],
          b_input:data[3],
          h_input:data[2].hour,
          m_input:data[2].month,
          date_type:1,
          is_leap:0,
          birth_date:data[2].result,
          moshi:0,
          word:0,
          unborn: 1,
        },
        success: (res:any) => {
          const patternName = /\/mzdf\/(.*?).html/g;
          const patternFs = /评分：(.*?)分/g;
          const nameInfo =  /<p class="over_hidden">(.*?)<\/p>/g;
          const fsInfo = /b">(.*?)分<\/b>/g;
          const nameList = res.data.match(patternName)
          const fsList = res.data.match(patternFs)
          const infoList =  res.data.match(nameInfo)
          const psList = res.data.match(fsInfo)
          const resultName = nameList ? nameList.map((a:any)=>{
            return a.split("_")[0].replace("/mzdf/","")
          }) : [];
          const resultPs = fsList ? fsList.map((a:any)=>{
            return a.replace("评分：","").replace("分：","")
          }) : [];
          const resultInfo = infoList ? infoList.map((a:any)=>{
            return a.replace('<p class="over_hidden">',"").replace("</p>","")
          }) : [];
          const resultFs = psList ? psList.map((a:any)=>{
            return a.replace('b">',"").replace("分</b>","")
          }) : [];
        resolve([resultName,resultPs,resultInfo,resultFs]);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  export const marketing = async (str1:string,str2:string,str3:string) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: "https://www.qudou100.com/apis/word/yxh",
        method: 'POST',
        header: {
          'Content-Type':'application/x-www-form-urlencoded',
        },
        data:{
          y1:str1,
          y2:str2,
          y3: str3,
        },
        success: (res:any) => {
        //  console.log(res.data.replace('<h2 align=\"center h2\">','').replace("</h2>",'').replace("<br>",""))
        //  //  
        resolve(res.data.data.replace('<h2 align="center h2">','').replace("</h2>",'').replace("<br>",""));
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  export const password = async (n1:string,type:string) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: "https://www.qudou100.com/apis/word/mores",
        method: 'POST',
        header: {
          'Content-Type':'application/x-www-form-urlencoded',
        },
        data:{
          text:n1,
          type:type,
          from: 'web',
        },
        success: (res:any) => {
        resolve(res.data.data);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  export const copywriting = async () => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: "https://www.qudou100.com/yule/wyy.html",
        success: (res:any) => {
        const regex = /<p[^>]*id="okres"[^>]*>(.*?)<\/p>/g;
        const match = res.data.toString().match(regex);
        resolve(match[0].replace("</p>","").replace('<p id="okres">',""));
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  export const xingmingDafen = async (xs:string,mz:string) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: "https://www.xingming.com/dafen/",
        method: 'POST',
        header: {
          'Content-Type':'application/x-www-form-urlencoded',
        },
        data:{
          action:'test',
          xs:xs,
          mz: mz,
        },
        success: (res:any) => {
        const regexTr = /<tr>.*?<\/tr>/gs;
        const regeFf = /<font[^>]*>(\d+)<\/font>/;
        const regexInfo = /<p>『含义』：.*?<\/p>/gs;
        const matchesTr = res.data.match(regexTr);
        const trList:any [] = []
        matchesTr.forEach(function(match:any) {
          const dataList = []
          const dataValue = match.matchAll(/<td[^>]*>(.*?)<\/td>/gs);  
          for (const datas of dataValue) {
            datas[1] !== "" && datas[1] !== " " &&  dataList.push(datas[1])
          }
          trList.push(dataList)
          
        });
        // const matches = matchesTr.matchAll(/<td[^>]*>(.*?)<\/td>/gs);  
       
        const matchesFf = res.data.match(regeFf);
        const matchesInfo = res.data.match(regexInfo).map((item:any)=>{
          return item.replace("<p>『含义』：","").replace("</p>","")
        });
        resolve([trList,matchesFf[1],matchesInfo[0],xs + mz]);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  export const flowerDate = async (str:string) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `https://srh.chacd.com/${str}/`,
        success: (res:any) => {
        const regex = /<strong[^>]*>(.*?)<\/strong>/g;
        const regexInfo = /<li class="list-group-item list-group-item-action">\s*<p>详细信息：<\/p>\s*([\s\S]*?)\s*<\/li>/g;
        const matchs = res.data.toString().match(regex);
        const matchInfos = res.data.toString().match(regexInfo);
        const dataList : any [] = []
        matchs.forEach(function(match:any) {
          const dataValue = match.matchAll(/<span[^>]*>(.*?)<\/span>/gs);  
          for (const datas of dataValue) {
            dataList.push(datas[1])
          }
          
        });
        matchInfos.forEach(function(match:any) {
          const dataValue = match.matchAll(/<p[^>]*>(.*?)<\/p>/gs);  
          for (const datas of dataValue) {
            datas[1] !== "详细信息：" && dataList.push(datas[1])
          }
        });

        resolve(dataList);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  } 

  export const futureName = async (name:string,gender:number) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: "https://www.dmnuo.com/douyin/futureName/",
        method: 'POST',
        header: {
          'Content-Type':'application/x-www-form-urlencoded',
        },
        data:{
          name:name,
          gender:gender
        },
        success: (res:any) => {
        let regex = /<strong class="text-danger">([^<]+)<\/strong>/;
        let matches = res.data.toString().match(regex);
        let text = matches[1];
        console.log(text)
        resolve(text);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }